package org.tulkas.browser;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpRequestBase;
import org.tulkas.config.GlobalConfig;
import org.tulkas.http.BaseConn;
import org.tulkas.http.ClientOptions;
import org.tulkas.util.FileUtil;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class DownloadItem extends BaseConn {
	private String destDir;

	private String destName;

	private Object metadata;

	private long expectedSize = -1;

	private String fromUrl = null;

	public DownloadItem(String url, String destDir) {
		this(url, destDir, null);
	}

	public DownloadItem(String url, String destDir, String destName) {
		this.setUrl(url);
		this.destDir = destDir;
		this.destName = destName;
	}

	public synchronized String getDestDir() {
		return destDir;
	}

	public synchronized void setDestDir(String destDir) {
		this.destDir = destDir;
	}

	public synchronized String getDestName() {
		return destName;
	}

	public synchronized void setDestName(String destName) {
		this.destName = destName;
	}

	public synchronized Object getMetadata() {
		return metadata;
	}

	public synchronized void setMetadata(Object metadata) {
		this.metadata = metadata;
	}

	public String getFromUrl() {
		return fromUrl;
	}

	public void setFromUrl(String fromUrl) {
		this.fromUrl = fromUrl;
	}

	public synchronized long getExpectedSize() {
		return expectedSize;
	}

	public synchronized void setExpectedSize(long expectedSize) {
		this.expectedSize = expectedSize;
	}

	@Override
	public synchronized HttpRequestBase createHttpRequest(ClientOptions options) {
		HttpGet get = new HttpGet(this.getUrl());
		return get;
	}

	public synchronized HttpRequestBase createHeadRequest(ClientOptions options) {
		HttpHead head = new HttpHead(this.getUrl());
		return head;
	}

	@Override
	public synchronized OutputStream createResponseStream() throws IOException {
		File test = new File(destDir);
		String path = null;
		if (test.isAbsolute()) {
			path = FileUtil.trimFilePath(destDir);
		} else {
			path = GlobalConfig.getInstance().getHomePath();
			String subDir = destDir;
			if (subDir != null) {
				if (!subDir.startsWith("/"))
					subDir = "/" + subDir;
				path += subDir;
			}
			path = FileUtil.trimFilePath(path);
		}
		new File(path).mkdirs();
		path += "/" + destName;

		return new BufferedOutputStream(new FileOutputStream(path));
	}

	@Override
	public synchronized void handleResponseContent(OutputStream resStream,
			ClientOptions options) throws IOException {
		resStream.close();
	}
}
